<?php
!defined('IN_FRAME') && die('404 Page');

/**
 * 前台页面
 */
class c_index extends Controller {
    
    /**
     * 类属性
     */
    public $objCatList = null;
    public $arrAssignGlobal = array();
    public $objSysConf = null;
    public $mdlContent = null;
    public $mdlContentPage = null;
    private $blnUseCache = true;
    
    /**
     * 构造函数,取相关全局数据
     */
    public function __construct() {
        $this->objCatList = Helper::loadModel('cat')->objTreeList;
        $this->objSysConf = Helper::loadModel('sys');
        $arrTemp = $this->objSysConf->get('site_name');
        $objTreeList = new TreeList();
        $objTreeList->arrSeper = array('　┊', '┈ ');
        $objTreeList->arrIdAll = $this->objCatList->arrIdAll;
        $objTreeList->arrIdRelationSimple = $this->objCatList->arrIdRelationSimple;
        $this->arrAssignGlobal = array(
            'objCatList' => $this->objCatList,
            'arrCatAll' => $this->objCatList->arrIdAll,
            'arrCatRoot' => $this->objCatList->arrIdRoot,
            'arrCatSon' => $this->objCatList->arrIdSon,
            'arrCatAncestor' => $this->objCatList->arrIdAncestor,
            'arrCatBackPath' => $this->objCatList->arrIdBackPath,
            'arrCatLevel' => $this->objCatList->arrIdLevel,
            'arrCatName' => $this->objCatList->arrNameAll,
            'strSiteName' => $arrTemp ? $arrTemp['val'] : 'MySite',
            'objTreeList' => $objTreeList,
            'catid' => '_0',
            'strDefaultSeoTitle' => $this->objSysConf->get('seo_t', false),
            'strDefaultSeoKeyword' => $this->objSysConf->get('seo_k', false),
            'strDefaultSeoDesc' => $this->objSysConf->get('seo_d', false)
        );
        $mdlManager = Helper::loadModel('manager');
        $this->blnUseCache = !$mdlManager->logined(); // 管理员不用看到缓存页面
    }
    
    /**
     * 首页
     */
    public function index() {
        if (isset($_GET['cat'])) {
            if (isset($this->arrAssignGlobal['arrCatAll']['_' . $_GET['cat']])) {
                $strTemp = HTTP_URL . '/' . $this->arrAssignGlobal['arrCatAll']['_' . $_GET['cat']]['name_en'];
                if (isset($_GET['key'])) {
                    $_GET['key'] = trim($_GET['key']);
                    !empty($_GET['key']) && $strTemp .= '-p1-' . urlencode($_GET['key']);
                }
                $strTemp .= '.html';
                Helper::jsLoadTo($strTemp);
            } else {
                Helper::jsLoadTo('/', '请选择栏目!');
            }
        } else {
            $this->blnUseCache && $this->_cache(1800, 'index'); // 缓存页面三十分钟
            $arrAssign = array(
                'strSeoTitle' => '',
                'strSeoKeyword' => '',
                'strSeoDesc' => '',
                'rootid' => 'index',
                'arrData' => array()
            );
            is_null($this->mdlContent) && $this->mdlContent = Helper::loadModel('content');
            $arrAssign['arrHot'] = $this->mdlContent->getHots();
            foreach ($this->arrAssignGlobal['arrCatRoot'] as $strTemp) {
                $arrAssign['arrData'][$strTemp] = $this->getList($strTemp, '', 1, 6, '`a`.`id` DESC', true);
            }
            $arrAssign['arrSlide'] = Helper::loadModel('slide')->getAll();
            $arrAssign = array_merge($arrAssign, $this->arrAssignGlobal);
            $this->_display('index.php', $arrAssign);
        }
    }
    
    /**
     * 处理面包屑
     */
    private function getBreadcrumb($_catid, $strKey = '') {
        $strRe = '<span>/</span><a href="' . HTTP_URL . '/' . $this->arrAssignGlobal['arrCatAll'][$_catid]['name_en'] . '.html">' . $this->arrAssignGlobal['arrCatAll'][$_catid]['name'] . '</a>';
        if (!empty($strKey)) {
            $strRe .= '<span>/</span>搜索:"<a href="' . HTTP_URL . '/' . $this->arrAssignGlobal['arrCatAll'][$_catid]['name_en'] . '-p1-' . urlencode($strKey) . '.html">' . Helper::strCut($strKey, 60) . '</a>"';
        }
        foreach ($this->arrAssignGlobal['arrCatBackPath'][$_catid] as $strTemp) {
            $strTemp = '<span>/</span><a href="' . HTTP_URL . '/' . $this->arrAssignGlobal['arrCatAll'][$strTemp]['name_en'] . '.html">' . $this->arrAssignGlobal['arrCatAll'][$strTemp]['name'] . '</a>';
            $strRe = $strTemp . $strRe;
        }
        $strRe = '<a href="' . HTTP_URL . '">首页</a>' . $strRe;
        return $strRe;
    }
    
    /**
     * 关于我们
     */
    public function aboutus() {
        $this->blnUseCache && $this->_cache(86400, 'aboutus');
        $arrAssign = array(
            'strSeoTitle' => '关于我们',
            'strBreadcrumb' => '<a href="' . HTTP_URL . '">首页</a><span>/</span><a href="' . HTTP_URL . '/aboutus.html">关于我们</a>'
        );
        $arrAssign = array_merge($arrAssign, $this->arrAssignGlobal);
        $this->_display('aboutus.php', $arrAssign);
    }
    
    /**
     * 版权声明
     */
    public function copyright() {
        $this->blnUseCache && $this->_cache(86400, 'copyright');
        $arrAssign = array(
            'strSeoTitle' => '版权声明',
            'strBreadcrumb' => '<a href="' . HTTP_URL . '">首页</a><span>/</span><a href="' . HTTP_URL . '/copyright.html">版权声明</a>'
        );
        $arrAssign = array_merge($arrAssign, $this->arrAssignGlobal);
        $this->_display('copyright.php', $arrAssign);
    }
    
    /**
     * 联系我们
     */
    public function contactus() {
        $this->blnUseCache && $this->_cache(86400, 'contactus');
        $arrAssign = array(
            'strSeoTitle' => '关于我们',
            'strBreadcrumb' => '<a href="' . HTTP_URL . '">首页</a><span>/</span><a href="' . HTTP_URL . '/contactus.html">联系我们</a>'
        );
        $arrAssign = array_merge($arrAssign, $this->arrAssignGlobal);
        $this->_display('contactus.php', $arrAssign);
    }
    
    /**
     * 记录页面浏览次数
     */
    public function setViewCnt() {
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        if (!Helper::isAjaxRequest()) {
            Helper::jsLoadTo('/', '页面不存在!');
        } elseif (is_numeric($id) && $id > 0 && !isset($_SESSION['viewed_' . $id])) {
            $_SESSION['viewed_' . $id] = 1;
            is_null($this->mdlContent) && $this->mdlContent = Helper::loadModel('content');
            $strSql = 'UPDATE `' . $this->mdlContent->table . '` SET `view_cnt` = `view_cnt` + 1 WHERE `rec_status` = 1 AND `id` = ' . $id;
            $this->mdlContent->query($strSql);
            die('1');
        }
        die('0');
    }
    
    /**
     * 取上/下一篇列表
     */
    private function getNeighborList($catid, $strCompOrder, $strSort = 'ASC') {
        $db = Db::getInstance();
        $strSql = ' GROUP BY `a`.`id` ORDER BY `a`.`list_order` ' . $strSort . ' LIMIT 0, 1';
        $strSql = 'SELECT `a`.* ' . $this->getSqlPart($catid, '', $strCompOrder) . $strSql;
        $re = $db->query($strSql);
        return $db->fetchResult($re);
    }
    
    /**
     * 取上/下一篇的数据
     */
    private function getNeighbor($cat, $intOrder) {
        $arrRe = array('prv' => '', 'next' => '');
        $arrTemp = $this->getNeighborList($cat, '>' . $intOrder);
        $arrTemp && $arrRe['prv'] = current($arrTemp);
        $arrTemp = $this->getNeighborList($cat, '<' . $intOrder, 'DESC');
        $arrTemp && $arrRe['next'] = current($arrTemp);
        return $arrRe;
    }
    
    /**
     * 显示详情页
     */
    private function show($cat, $id, $intPage = 1) {
        $this->blnUseCache && $this->_cache(1800, $cat . '_' . $id . '_' . $intPage); // 缓存页面三十分钟
        $arrData = null;
        is_null($this->mdlContent) && $this->mdlContent = Helper::loadModel('content');
        $id * $cat > 0 && $arrData = $this->mdlContent->getOne(array('id' => $id, 'cat_id' => $cat, 'rec_status' => 1));
        if ($arrData) {
            is_null($this->mdlContentPage) && $this->mdlContentPage = Helper::loadModel('content_page');
            $intPageCnt = $this->mdlContentPage->count(array('content_id' => $id, 'rec_status' => 1));
            if ($intPage > $intPageCnt) {
                define('DO_NOT_CACHE_ME', 1);
                $intPage = $intPageCnt;
            }
            $arrAssign = array('arrData' => $arrData);
            $arrAssign['strSeoTitle'] = $arrData['seo_t'];
            $arrAssign['strSeoKeyword'] = $arrData['seo_k'];
            $arrAssign['strSeoDesc'] = $arrData['seo_d'];
            $intCatId = '_' . $arrData['cat_id'];
            $this->arrAssignGlobal['catid'] = $intCatId;
            $intRootCatId = $intCatId;
            $this->arrAssignGlobal['arrCatAncestor'][$intCatId] && $intRootCatId = $this->arrAssignGlobal['arrCatAncestor'][$intCatId];
            $arrAssign['rootid'] = $intRootCatId;
            $arrAssign['strBreadcrumb'] = $this->getBreadcrumb($intCatId);
            $strTemp = HTTP_URL . '/' . $this->arrAssignGlobal['arrCatAll'][$intCatId]['name_en'] . '-' . $id . '.html';
            $strTemp_ = HTTP_URL . '/' . $this->arrAssignGlobal['arrCatAll'][$intCatId]['name_en'] . '-' . $id . '-p__PAGE__.html';
            $arrAssign['strBreadcrumb'] .= '<span>/</span><a href="' . $strTemp . '">' . Helper::strCut($arrData['title'], 81) . '</a>';
            $arrAssign['arrDataPage'] = $this->mdlContentPage->select(array('content_id' => $id, 'rec_status' => 1), '*', 'ORDER BY `list_order` LIMIT ' . ($intPage - 1) . ', 1');
            $arrAssign['arrDataPage'] = current($arrAssign['arrDataPage']);
            $arrAssign['strPager'] = $this->getObjPager($strTemp, $intPageCnt, 1, $strTemp_, $intPage)->genHtml();
            $arrAssign['strSelfUrl'] = $strTemp;
            $arrAssign['arrNei'] = $this->getNeighbor($intRootCatId, $arrData['list_order']);
            $arrAssign = array_merge($arrAssign, $this->arrAssignGlobal);
            $this->_display('show.php', $arrAssign);
        } else {
            Helper::jsLoadTo('/', '页面不存在!');
        }
    }
    
    /**
     * 构造SQL
     */
    private function getSqlPart($catid, $key = '', $strCompOrder = '', $blnThumb = false) {
        $catid = substr($catid, 1);
        is_null($this->mdlContent) && $this->mdlContent = Helper::loadModel('content');
        is_null($this->mdlContentPage) && $this->mdlContentPage = Helper::loadModel('content_page');
        $strSql = 'FROM `' . $this->mdlContent->table . '` AS `a`, `' . $this->mdlContentPage->table . '` AS `b` ';
        $strSql .= 'WHERE `a`.`id` = `b`.`content_id` AND `a`.`rec_status` > 0 AND `a`.`cat_id` IN (';
        $arrTemp = array($catid);
        if (isset($this->objCatList->arrIdChildren['_' . $catid])) {
            $arrTemp = array_merge($arrTemp, $this->objCatList->arrIdChildren['_' . $catid]);
        }
        $strSql .= str_replace('_', '', implode(', ', $arrTemp)) . ')';
        if (!empty($key)) {
            $key_ = $key;
            if (mb_strlen($key, 'utf8') > 4) {
                $key_ = Helper::fenCi($key_);
            }
            if (false && !empty($key_)) { // 暂时只用LIKE作全文搜索
                $key = Helper::genIndexStr($key_);
                $strSql .= ' AND (MATCH (`a`.`search_index`) AGAINST ("' . $key . '" IN BOOLEAN MODE) OR ';
                $strSql .= 'MATCH (`b`.`search_index`) AGAINST ("' . $key . '" IN BOOLEAN MODE))';
            } else {
                $key = 'LIKE "%' . addslashes($key) . '%"';
                $strSql .= ' AND (`a`.`title` ' . $key . ' OR `a`.`desc` ' . $key . ' OR `a`.`tags` ' . $key . ' OR ';
                $strSql .= '`b`.`title` ' . $key . ' OR `b`.`txt` ' . $key . ')';
            }
        }
        if (!empty($strCompOrder)) {
            $strSql .= ' AND `a`.`list_order` ' . $strCompOrder;
        }
        if ($blnThumb) {
            $strSql .= ' AND `a`.`thumb` <> ""';
        }
        return $strSql;
    }
    
    /**
     * 取列表统计
     */
    private function getCount($catid, $key = '') {
        $db = Db::getInstance();
        $re = $db->query('SELECT COUNT(DISTINCT `a`.`id`) AS `cnt` ' . $this->getSqlPart($catid, $key));
        $re = $db->fetchResult($re);
        $re = current($re);
        return $re['cnt'];
    }
    
    /**
     * 取列表数组
     */
    private function getList($catid, $key = '', $intPage = 1, $intCntPerPage = 10, $strOrder = '`a`.`is_top` DESC, `a`.`list_order` DESC', $blnThumb = false) {
        $db = Db::getInstance();
        $strSql = ' GROUP BY `a`.`id` ORDER BY ' . $strOrder;
        $strSql .= ' LIMIT ' . (($intPage - 1) * $intCntPerPage) . ', ' . $intCntPerPage;
        $re = $db->query('SELECT `a`.* ' . $this->getSqlPart($catid, $key, '', $blnThumb) . $strSql);
        return $db->fetchResult($re);
    }
    
    /**
     * 取分页对象
     */
    private function getObjPager($strUrl, $intCnt, $intPer = 10, $get = null, $intCur = 1, $blnFirst = false) {
        is_null($get) && $get = $_GET;
        $objPager = new Pager($strUrl, $get, $intCnt);
        if (!is_array($get)) {
            $objPager->strVarName = '__PAGE__';
            $objPager->intCurrPage = $intCur;
            $objPager->blnShowFirst = $blnFirst;
        }
        $objPager->intItemsPerPage = $intPer;
        $objPager->strDivCssClass = 'page';
        $objPager->strHtmlStart = '';
        $objPager->strHtmlEnd = '';
        $objPager->strCurrCssClass = 'current';
        $objPager->blnNeedMore = false;
        return $objPager;
    }
    
    /**
     * URL静态处理
     */
    public function _remap($str) {
        $strCall = '';
        $arrPara = array();
        if (isset($this->arrAssignGlobal['arrCatName'][$str])) { // 列表页之第一页
            $arrPara[0] = $this->arrAssignGlobal['arrCatName'][$str]['id'];
            $strCall = 'lists';
        } elseif (($intTemp = strpos($str, '-')) > 0) { // 带分页和其它参数
            $strTemp = substr($str, 0, $intTemp);
            if (isset($this->arrAssignGlobal['arrCatName'][$strTemp])) {
                $arrPara[0] = $this->arrAssignGlobal['arrCatName'][$strTemp]['id'];
                $strTemp = substr($str, $intTemp + 1);
                if (preg_match('/^p[1-9]\d*(\-\S+)?$/', $strTemp) == 1) { // 列表页
                    if (($intTemp = strpos($strTemp, '-')) > 1) { // 带关键词搜索和分页
                        $arrPara[1] = substr($strTemp, 1, $intTemp - 1);
                        $arrPara[2] = urldecode(substr($strTemp, $intTemp + 1));
                    } else { // 只带分页
                        $arrPara[1] = substr($strTemp, 1);
                    }
                    $strCall = 'lists';
                } elseif (preg_match('/^[1-9]\d*(\-p[1-9]\d*)?$/', $strTemp) == 1) { // 详情页
                    if (($intTemp = strpos($strTemp, '-')) > 0) { // 带分页
                        $arrPara[1] = substr($strTemp, 0, $intTemp);
                        $arrPara[2] = substr($strTemp, $intTemp + 2);
                    } else { // 不带分页
                        $arrPara[1] = $strTemp;
                    }
                    $strCall = 'show';
                }
            }
        }
        if (empty($strCall)) {
            Helper::jsLoadTo('/', '页面不存在!');
        } else {
            call_user_func_array(array(&$this, $strCall), $arrPara);
        }
    }
    
    /**
     * 列表页
     */
    private function lists($intCatId, $intPage = 1, $strKey = '') {
        $arrAssign = array();
        $intCatId = '_' . $intCatId;
        $this->blnUseCache && $this->_cache(1800, $intCatId . '_' . $intPage . '_' . md5($strKey)); // 缓存页面三十分钟
        $intCnt = $this->getCount($intCatId, $strKey);
        $intPer = 10;
        $intPagesCnt = Pager::getPagesCnt($intCnt, $intPer);
        if ($intPage > $intPagesCnt) {
            define('DO_NOT_CACHE_ME', 1);
            $intPage = $intPagesCnt;
        }
        $arrAssign['strKey'] = $strKey;
        $intRootCatId = $intCatId;
        $this->arrAssignGlobal['arrCatAncestor'][$intCatId] && $intRootCatId = $this->arrAssignGlobal['arrCatAncestor'][$intCatId];
        $this->arrAssignGlobal['catid'] = $intCatId;
        $arrAssign['rootid'] = $intRootCatId;
        $arrAssign['strSeoTitle'] = $this->arrAssignGlobal['arrCatAll'][$intCatId]['seo_t'];
        $arrAssign['strSeoKeyword'] = $this->arrAssignGlobal['arrCatAll'][$intCatId]['seo_k'];
        $arrAssign['strSeoDesc'] = $this->arrAssignGlobal['arrCatAll'][$intCatId]['seo_d'];
        $arrAssign['strBreadcrumb'] = $this->getBreadcrumb($intCatId, $strKey);
        $arrAssign['arrList'] = $this->getList($intCatId, $strKey, $intPage, $intPer);
        $strTemp = HTTP_URL . '/' . $this->arrAssignGlobal['arrCatAll'][$intCatId]['name_en'] . '.html';
        $strTemp_ = HTTP_URL . '/' . $this->arrAssignGlobal['arrCatAll'][$intCatId]['name_en'] . '-p__PAGE__';
        !empty($strKey) && $strTemp_ .= '-' . urlencode($strKey);
        $strTemp_ .= '.html';
        $arrAssign['strPager'] = $this->getObjPager($strTemp, $intCnt, $intPer, $strTemp_, $intPage, !empty($strKey))->genHtml();
        $arrAssign = array_merge($arrAssign, $this->arrAssignGlobal);
        $this->_display('lists.php', $arrAssign);
    }
}